package com.hobart.learning.lagou.edu.IPersistence.sqlSession;

import com.hobart.learning.lagou.edu.IPersistence.pojo.Configuration;
import com.hobart.learning.lagou.edu.IPersistence.pojo.MappedStatement;
import org.apache.commons.collections4.CollectionUtils;

import java.beans.IntrospectionException;
import java.lang.reflect.*;
import java.sql.SQLException;
import java.util.List;

/**
 * @author ：hobart
 * @date ：Created in 2020-11-11 0:08
 * @description：SqlSession 类
 * @modified By：
 * @version: 1$
 */
public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws IllegalAccessException, ClassNotFoundException, IntrospectionException, InstantiationException, SQLException, InvocationTargetException, NoSuchFieldException {
        SimpleExcutor simpleExcutor = new SimpleExcutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        List<Object> list = simpleExcutor.query(configuration, mappedStatement, params);
        return (List<E>) list;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws IllegalAccessException, IntrospectionException, InstantiationException, NoSuchFieldException, SQLException, InvocationTargetException, ClassNotFoundException {
        List<Object> objects = selectList(statementId, params);
        if(CollectionUtils.isNotEmpty(objects)){
            if(objects.size()==1){
                return (T) objects.get(0);
            } else {
                throw new  RuntimeException("The query result requires one, but returns a collection!");
            }
        }

        return null;
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        // 使用JDK动态代理 为DAO生成代理实现类 然后返回

        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            // proxy 当前代理对象的 引用
            // method 当前被调用的方法的 引用
            // args 被调用方法的 参数
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                // 底层还是去执行JDBC 代码，
                // 根据不同情况来调用 selectList or selectOne
                // 准备参数 1.statementId sql的唯一标识namespace.id=接口权限名.方法名
                //         2.params: srgs
                // 方法名：
                String methodName = method.getName();
                // 类名
                String className = method.getDeclaringClass().getName();

                String statementId = className + "." + methodName;
                System.out.println("statementId = "+statementId);
                // 准备参数2:params： args
                // 通过 methodName 判断执行 那个 方法
                if("insert".equals(methodName)){
                    return insert(statementId, args);
                } else if("update".equals(methodName)){
                    return update(statementId, args);
                } else if("delete".equals(methodName)){
                    return delete(statementId, args);
                } else {

                    // 获取被调用的方法的返回值类型
                    Type genericReturnType = method.getGenericReturnType();
                    // 判断是否进行了 泛型参数化
                    if(genericReturnType instanceof  ParameterizedType){
                        List<Object>  objects = selectList(statementId, args);
                        return objects;
                    }

                    return selectOne(statementId, args);
                }


            }
        });

        return (T) proxyInstance;
    }

    @Override
    public int insert(String statementId, Object... params) throws IllegalAccessException, IntrospectionException, InstantiationException, NoSuchFieldException, SQLException, InvocationTargetException, ClassNotFoundException {
        SimpleExcutor simpleExcutor = new SimpleExcutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        int flag = simpleExcutor.insert(configuration, mappedStatement, params);
        if(flag != -1){
            return flag;
        } else {
            throw new  RuntimeException("Insert the wrong!");
        }
    }

    @Override
    public int update(String statementId, Object... params) throws IllegalAccessException, IntrospectionException, InstantiationException, NoSuchFieldException, SQLException, InvocationTargetException, ClassNotFoundException {
        SimpleExcutor simpleExcutor = new SimpleExcutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        int flag = simpleExcutor.update(configuration, mappedStatement, params);
        if(flag != -1){
            return flag;
        } else {
            throw new  RuntimeException("update the wrong!");
        }
    }

    @Override
    public int delete(String statementId, Object... params) throws IllegalAccessException, IntrospectionException, InstantiationException, NoSuchFieldException, SQLException, InvocationTargetException, ClassNotFoundException {
        SimpleExcutor simpleExcutor = new SimpleExcutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        int flag = simpleExcutor.delete(configuration, mappedStatement, params);
        if(flag != -1){
            return flag;
        } else {
            throw new  RuntimeException("delete the wrong!");
        }
    }
}
